package io.renren.modules.app.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.common.utils.R;
import io.renren.modules.app.dao.*;
import io.renren.modules.app.entity.*;
import io.renren.modules.app.service.ImMomentService;
import io.renren.modules.app.tio.TioServerConfig;
import io.renren.modules.app.tio.WsOnlineContext;
import io.renren.modules.app.utils.ChatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;


@Service("imMomentService")
public class ImMomentServiceImpl extends ServiceImpl<ImMomentDao, ImMomentEntity> implements ImMomentService {


    @Autowired
    private ImFriendDao imFriendDao;
    @Autowired
    private ImMomentDao imMomentDao;
    @Autowired
    private ImMomentTimelineDao imMomentTimelineDao;
    @Autowired
    private ImMomentLikeDao imMomentLikeDao;
    @Autowired
    private ImMomentCommentDao imMomentCommentDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ImMomentEntity> page = this.page(
                new Query<ImMomentEntity>().getPage(params),
                new QueryWrapper<ImMomentEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public R create(UserEntity user, ImMomentEntity imMoment) {
        imMoment.setUserId(user.getUserId().intValue());
        imMoment.setCreatedAt(new Date());
        imMoment.setUpdatedAt(new Date());
        //新增
        this.baseMapper.insert(imMoment);
        // 推送到好友的时间轴
        //获取所有好友
        List<ImFriendEntity> list = imFriendDao.selectList(new QueryWrapper<ImFriendEntity>().eq("user_id",user.getUserId()).eq("isblack",0));
        String [] sees = imMoment.getSee().split(":");
        String oType = sees[0];
        String [] ids = null;
        if((oType.equals("only") || oType.equals("except")) && !sees[1].equals("")){
            ids = sees[1].split(",");
        }
        ImMomentTimelineEntity mTl = new ImMomentTimelineEntity();
        mTl.setCreatedAt(new Date());
        mTl.setUpdatedAt(new Date());
        mTl.setMomentId(imMoment.getId());
        mTl.setOwn(0);

        // 消息推送
        Message message = new Message();
        message.setType("new");
        message.setAvatar(user.getAvatar());
        message.setUser_id(user.getUserId().toString());
        SendInfo sendInfo = new SendInfo();
        sendInfo.setCode(ChatUtils.MSG_MESSAGE);
        sendInfo.setMessage(message);
        sendInfo.setMsg("moment");
        WsResponse wsResponse = null;
        try {
            wsResponse = WsResponse.fromText(new ObjectMapper().writeValueAsString(sendInfo), TioServerConfig.CHARSET);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        ChannelContext cco = WsOnlineContext.getChannelContextByUser(user.getUserId().toString());

        if("all".equals(oType)){//公开
            for(ImFriendEntity it : list){
                mTl.setUserId(it.getFriendId());
                imMomentTimelineDao.insert(mTl);
                Tio.sendToUser(cco.groupContext, it.getFriendId().toString(), wsResponse);
            }
        }else if("only".equals(oType) || "except".equals(oType)){//仅谁可看
            for (String id : ids){
                mTl.setUserId(Integer.parseInt(id));
                imMomentTimelineDao.insert(mTl);
                Tio.sendToUser(cco.groupContext, id, wsResponse);
            }
        }else if("except".equals(oType)){//谁不可看
            for(ImFriendEntity it : list){
                for (String id : ids){
                    if(id.equals(it.getFriendId().toString())){
                        break;
                    }
                }
                mTl.setUserId(it.getFriendId());
                imMomentTimelineDao.insert(mTl);
                Tio.sendToUser(cco.groupContext, it.getFriendId().toString(), wsResponse);
            }

        }
        //自己
        mTl.setOwn(1);
        mTl.setUserId(user.getUserId().intValue());
        imMomentTimelineDao.insert(mTl);
        // 提醒用户
        if(!imMoment.getRemind().equals("")){
            String [] remind = imMoment.getRemind().split(",");
            message.setType("remind");
            sendInfo.setMsg("moment");
            sendInfo.setMessage(message);
            for(String id : remind){
                Tio.sendToUser(cco.groupContext, id, wsResponse);
            }
        }
        return R.ok();
    }

    @Override
    public R timeline(UserEntity user, ImMomentEntity imMoment) {

        //能看到的  所以动态
        List<ImMomentEntity> list = imMomentDao.selectListByUserId(user.getUserId());
        for(ImMomentEntity it : list){
            List<ImMomentLikeEntity> li = imMomentLikeDao.selectListByMid(it.getId());
            it.setLikes(li);
            List<Options> urList = new ArrayList<>();
            List<ImMomentCommentEntity> mcList = imMomentCommentDao.selectUrList(it.getId());
            for (ImMomentCommentEntity bean :mcList){
                Options o = new Options();
                o.setContent(bean.getContent());
                User u = new User();
                u.setId(bean.getUid());
                u.setName(bean.getUname());
                o.setUser(u);
                Reply r = new Reply();
                if(bean.getRid() != null){
                    r.setId(bean.getRid());
                    r.setName(bean.getRname());
                    o.setReply(r);
                }else {
                    o.setReply(null);
                }
                urList.add(o);
            }
            it.setComments(urList);
        }
        return R.ok(list);
    }

    @Override
    public R like(UserEntity user, ImMomentEntity imMoment) {
        imMoment=imMomentDao.selectById(imMoment);
        ImMomentTimelineEntity bean = imMomentTimelineDao.selectOne(new QueryWrapper<ImMomentTimelineEntity>().eq("user_id",user.getUserId()).eq("moment_id",imMoment.getId()));
        if(bean==null)return R.error("朋友圈消息不存在");
        ImMomentLikeEntity like = imMomentLikeDao.selectOne(new QueryWrapper<ImMomentLikeEntity>().eq("user_id",user.getUserId()).eq("moment_id",imMoment.getId()));
        if(like==null){
            like = new ImMomentLikeEntity();
            like.setCreatedAt(new Date());
            like.setUpdatedAt(new Date());
            like.setUserId(user.getUserId().intValue());
            like.setMomentId(imMoment.getId());
            imMomentLikeDao.insert(like);
            // 消息推送
            Message message = new Message();
            message.setType("like");
            message.setAvatar(user.getAvatar());
            message.setUser_id(user.getUserId().toString());
            SendInfo sendInfo = new SendInfo();
            sendInfo.setCode(ChatUtils.MSG_MESSAGE);
            sendInfo.setMessage(message);
            sendInfo.setMsg("moment");
            WsResponse wsResponse = null;
            try {
                wsResponse = WsResponse.fromText(new ObjectMapper().writeValueAsString(sendInfo), TioServerConfig.CHARSET);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            ChannelContext cco = WsOnlineContext.getChannelContextByUser(user.getUserId().toString());

            //通知作者
            if(user.getUserId().intValue()!=imMoment.getUserId()){
                Tio.sendToUser(cco.groupContext, imMoment.getUserId().toString(), wsResponse);
            }
            //通知相关点赞人员
            List<ImMomentLikeEntity> list = imMomentLikeDao.selectList(new QueryWrapper<ImMomentLikeEntity>().eq("moment_id",imMoment.getId()));
            for (ImMomentLikeEntity it : list) {
                if(it.getUserId()!=user.getUserId().intValue()){
                    Tio.sendToUser(cco.groupContext, it.getUserId().toString(), wsResponse);
                }
            }
        }else{
            imMomentLikeDao.deleteById(like);
        }


        return R.ok();
    }

    @Override
    public R comment(UserEntity user, ImMomentCommentEntity imMomentComment) {
        ImMomentEntity imMoment=imMomentDao.selectById(imMomentComment.getMomentId());
        ImMomentTimelineEntity bean = imMomentTimelineDao.selectOne(new QueryWrapper<ImMomentTimelineEntity>().eq("user_id",user.getUserId()).eq("moment_id",imMoment.getId()));
        if(bean==null)return R.error("朋友圈消息不存在");

        imMomentComment.setUserId(user.getUserId().intValue());
        imMomentComment.setCreatedAt(new Date());
        imMomentComment.setUpdatedAt(new Date());
        imMomentCommentDao.insert(imMomentComment);

        // 消息推送
        Message message = new Message();
        message.setType("comment");
        message.setAvatar(user.getAvatar());
        message.setUser_id(user.getUserId().toString());
        SendInfo sendInfo = new SendInfo();
        sendInfo.setCode(ChatUtils.MSG_MESSAGE);
        sendInfo.setMessage(message);
        sendInfo.setMsg("moment");
        WsResponse wsResponse = null;
        try {
            wsResponse = WsResponse.fromText(new ObjectMapper().writeValueAsString(sendInfo), TioServerConfig.CHARSET);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        ChannelContext cco = WsOnlineContext.getChannelContextByUser(user.getUserId().toString());

        //通知作者
        if(user.getUserId().intValue()!=imMoment.getUserId()){
            Tio.sendToUser(cco.groupContext, imMoment.getUserId().toString(), wsResponse);
        }
        //通知相关点赞人员
        /*List<ImMomentLikeEntity> list = imMomentLikeDao.selectList(new QueryWrapper<ImMomentLikeEntity>().eq("moment_id",imMoment.getId()));
        for (ImMomentLikeEntity it : list) {
            if(it.getUserId()!=user.getUserId().intValue()){
                Tio.sendToUser(cco.groupContext, it.getUserId().toString(), wsResponse);
            }
        }*/
        // 通知被回复人
        if(imMomentComment.getReplyId()>0){
            Tio.sendToUser(cco.groupContext, imMomentComment.getReplyId().toString(), wsResponse);
        }
        return R.ok();
    }

}
